package com.ef.web.action;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.write.BorderLineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Criteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;

import com.ef.constant.ELeadsDealType;
import com.ef.constant.ELeadsType;
import com.ef.domain.Leads;
import com.ef.domain.LeadsDealHistory;
import com.ef.domain.User;
import com.ef.util.CustomExample;
import com.ef.util.LeadsExample;
import com.ef.util.PaginationSupport;

public class TMAssignAction extends LeadsAction {

	private static final long serialVersionUID = 1L;

	private Map<String, String> tms;

	private String noTm = "NotAssigned";

	private Long[] selMarketingPolicy;

	private Integer pagesize = 100;

	private Map<String, String> cms;
	
	/**
	 * 没有CC的帐号
	 */
	private boolean noCc = true;

	public boolean isNoCc() {
		return noCc;
	}

	public void setNoCc(boolean noCc) {
		this.noCc = noCc;
	}

	public Integer getPagesize() {
		return pagesize;
	}

	public void setPagesize(Integer pagesize) {
		this.pagesize = pagesize;
	}

	public Long[] getSelMarketingPolicy() {
		return selMarketingPolicy;
	}

	public void setSelMarketingPolicy(Long[] selMarketingPolicy) {
		this.selMarketingPolicy = selMarketingPolicy;
	}

	@SuppressWarnings("serial")
	public String list() {
		fetchListData();
		CustomExample<Leads> example = new LeadsExample(this.getModel(),
				Leads.class) {
			public void appendCondition(Criteria criteria) {
				super.appendCondition(criteria);
				if (selTmCall!=null){
				    criteria.add(Restrictions.eq("tmCall",selTmCall));
				}
				if (entity.getLeadsType() == null) {// 未选择leadstype
					criteria.add(Restrictions.or(Restrictions.and(Restrictions
							.ne("leadsType", ELeadsType.CarOwner), Restrictions
							.ne("leadsType", ELeadsType.Internet)),
							Restrictions.isNull("leadsType")));
				} else if (entity.getLeadsType().equals(ELeadsType.CarOwner)
						|| entity.getLeadsType().equals(ELeadsType.Internet)) {
					// 一条不选
					criteria.add(Restrictions.isNull("id"));
				}
				if (entity.getTm() == null || entity.getTm().getName() == null
						|| entity.getTm().getName().length() == 0) {
					if (noTm.equalsIgnoreCase("NotAssigned")) {
						criteria.add(Restrictions.isNull("tm"));
					} else if (noTm.equalsIgnoreCase("Assigned")) {
						criteria.add(Restrictions.isNotNull("tm"));
					}
				}
				if (noCc){
					criteria.add(Restrictions.isNull("cc"));
				}
				if (selMarketingPolicy != null && selMarketingPolicy.length > 0) {
					criteria.createCriteria("marketingPolicy",
							"marketingPolicy");
					Disjunction or = Restrictions.disjunction();
					Property myProperty = Property
							.forName("marketingPolicy.id");
					for (Long mid : selMarketingPolicy) {
						or.add(myProperty.eq(mid));
					}
					criteria.add(or);
				}
			}
		};
		example.addBetweenDateProperty("createTime", selCreateStartTime,
				selCreateEndTime);
		example.addBetweenDateProperty("setApptTime", selSetApptStartTime,
				selSetApptEndTime);
		example.addBetweenDateProperty("showTime", selShowStartTime,
				selShowEndTime);
		example.addBetweenDateProperty("lastEventTime", selLastTouchStartTime,
				selLastTouchEndTime);
		example.addBetweenDateProperty("payTime", selPayStartTime,
				selPayEndTime);
		example.addBetweenDateProperty("tmAssignTime", selAssignTmStartTime,
				selAssignTmEndTime);
		example.addBetweenDateProperty("initVisitTime", selInitVisitStartTime,
				selInitVisitEndTime);
		this.listResult = leadsService.findByExample(example, this
				.getStartIndex(), pagesize);
		return LIST;
	};

	@SuppressWarnings("serial")
	public String exportByTMMan() {
		CustomExample<Leads> example = new LeadsExample(this.getModel(),
				Leads.class) {
			public void appendCondition(Criteria criteria) {
				super.appendCondition(criteria);
				if (entity.getLeadsType() == null) {
					// 没有leadstype,
					criteria.add(Restrictions.or(Restrictions.and(Restrictions
							.ne("leadsType", ELeadsType.CarOwner), Restrictions
							.ne("leadsType", ELeadsType.Internet)),
							Restrictions.isNull("leadsType")));
				} else if (entity.getLeadsType().equals(ELeadsType.CarOwner)
						|| entity.getLeadsType().equals(ELeadsType.Internet)) {
					// 一条不选
					criteria.add(Restrictions.isNull("id"));
				}
				if (entity.getTm() == null || entity.getTm().getName() == null
						|| entity.getTm().getName().length() == 0) {
					if (noTm.equalsIgnoreCase("NotAssigned")) {
						criteria.add(Restrictions.isNull("tm"));
					} else if (noTm.equalsIgnoreCase("Assigned")) {
						criteria.add(Restrictions.isNotNull("tm"));
					}
				}
				if (selMarketingPolicy != null && selMarketingPolicy.length > 0) {
					criteria.createCriteria("marketingPolicy",
							"marketingPolicy");
					Disjunction or = Restrictions.disjunction();
					Property myProperty = Property
							.forName("marketingPolicy.id");
					for (Long mid : selMarketingPolicy) {
						or.add(myProperty.eq(mid));
					}
					criteria.add(or);
				}
    		}
		};
		example.addBetweenDateProperty("createTime", selCreateStartTime,
				selCreateEndTime);
		example.addBetweenDateProperty("setApptTime", selSetApptStartTime,
				selSetApptEndTime);
		example.addBetweenDateProperty("showTime", selShowStartTime,
				selShowEndTime);
		example.addBetweenDateProperty("lastEventTime", selLastTouchStartTime,
				selLastTouchEndTime);
		example.addBetweenDateProperty("payTime", selPayStartTime,
				selPayEndTime);
		example.addBetweenDateProperty("tmAssignTime", selAssignTmStartTime,
				selAssignTmEndTime);
		example.addBetweenDateProperty("initVisitTime", selInitVisitStartTime,
				selInitVisitEndTime);
		PaginationSupport<Leads> result = leadsService.findByExample(example,
				0, 60000); // 只显示1000个最多。
		HttpServletRequest request = getRequest();
		HttpServletResponse response = getResponse();

		response.setContentType("application/ms-excel;charset=UTF-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=export leads.xls");

		File tempPath = new File(ServletActionContext.getServletContext()
				.getRealPath("/temp"));
		if (!tempPath.exists()) {
			tempPath.mkdirs();
		}
		WritableWorkbook workBook;

		File exportFile = new File(ServletActionContext.getServletContext()
				.getRealPath("/temp/exportleads.xls"));
		try {
			// TODO styles
			WritableFont font = new WritableFont(WritableFont.TIMES, 12,
					WritableFont.BOLD);
			WritableCellFormat headStyle = new WritableCellFormat(font);
			headStyle.setAlignment(Alignment.CENTRE);
			WritableCellFormat titleStyle = new WritableCellFormat(font);
			titleStyle.setAlignment(Alignment.CENTRE);
			titleStyle.setWrap(false);
			titleStyle.setBorder(Border.ALL, BorderLineStyle.THIN);
			WritableFont font_content = new WritableFont(WritableFont.TIMES, 10);
			WritableCellFormat contentStyle = new WritableCellFormat(
					font_content);
			contentStyle.setAlignment(Alignment.CENTRE);
			contentStyle.setBorder(Border.ALL, BorderLineStyle.THIN);
			contentStyle.setWrap(false);
			workBook = Workbook.createWorkbook(exportFile);
			workBook.setProtected(false);
			// create sheets
			WritableSheet activeSheet = workBook.createSheet("Export Leads", 0);
			activeSheet.addCell(new Label(0, 0, "Name ", titleStyle));
			activeSheet.addCell(new Label(1, 0, "Age   ", titleStyle));
			activeSheet.addCell(new Label(2, 0, "Tel   ", titleStyle));
			activeSheet
					.addCell(new Label(3, 0, "Marketing Policy ", titleStyle));
			activeSheet.addCell(new Label(4, 0, "Marketing Plan ", titleStyle));
			activeSheet.addCell(new Label(5, 0, "AdChannel ", titleStyle));
			activeSheet.addCell(new Label(6, 0, "  PTE ", titleStyle));
			activeSheet
					.addCell(new Label(7, 0, "Init visit time ", titleStyle));
			activeSheet.addCell(new Label(8, 0, "TM   ", titleStyle));
			activeSheet.addCell(new Label(9, 0, "Assign Time   ", titleStyle));
			activeSheet.addCell(new Label(10, 0, "Comments  ", titleStyle));
			activeSheet.addCell(new Label(11, 0, "  Status ", titleStyle));
			activeSheet.addCell(new Label(12, 0, "  Area ", titleStyle));
			int size = result.getItems().size();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			for (int i = 0; i < size; i++) {
				Leads leads = result.getItems().get(i);
				activeSheet.addCell(new Label(0, i + 1, leads.getName(),
						contentStyle));
				activeSheet.addCell(new Label(1, i + 1, leads.getAge(),
						contentStyle));
				activeSheet.addCell(new Label(2, i + 1,
						""/* leads.getTelInfo() */, contentStyle));
				if (leads.getMarketingPolicy() != null)
					activeSheet.addCell(new Label(3, i + 1, leads
							.getMarketingPolicy().getName(), contentStyle));
				else
					activeSheet.addCell(new Label(3, i + 1, "", contentStyle));
				if (leads.getMarketingPlan() != null)
					activeSheet.addCell(new Label(4, i + 1, leads
							.getMarketingPlan().getName(), contentStyle));
				else
					activeSheet.addCell(new Label(4, i + 1, "", contentStyle));
				if (leads.getAdChannel() != null)
					activeSheet.addCell(new Label(5, i + 1, leads
							.getAdChannel().getName(), contentStyle));
				else
					activeSheet.addCell(new Label(5, i + 1, "", contentStyle));
				if (leads.getPte() != null) {
					activeSheet.addCell(new Label(6, i + 1, leads.getPte()
							.getName(), contentStyle));
				} else {
					activeSheet.addCell(new Label(6, i + 1, "", contentStyle));
				}
				if (leads.getInitVisitTime() != null)
					activeSheet.addCell(new Label(7, i + 1, sdf.format(leads
							.getInitVisitTime()), contentStyle));
				else
					activeSheet.addCell(new Label(7, i + 1, "", contentStyle));

				activeSheet.addCell(new Label(8, i + 1,
						(leads.getTm() == null ? "" : leads.getTm().getName()),
						contentStyle));
				if (leads.getTmAssignTime() != null)
					activeSheet.addCell(new Label(9, i + 1, sdf.format(leads
							.getTmAssignTime()), contentStyle));
				else
					activeSheet.addCell(new Label(9, i + 1, "", contentStyle));
				activeSheet.addCell(new Label(10, i + 1, leads.getComments(),
						contentStyle));
				activeSheet.addCell(new Label(11, i + 1, (leads
						.getLeadsStatus() == null ? "" : leads.getLeadsStatus()
						.toString()), contentStyle));
				if (leads.getCity() != null)
					activeSheet.addCell(new Label(12, i + 1, leads
							.getCity(), contentStyle));
				else
					activeSheet.addCell(new Label(12, i + 1, "", contentStyle));
			}
			workBook.write();
			workBook.close();

		} catch (IOException e) {
			e.printStackTrace();
		} catch (WriteException e) {
			e.printStackTrace();
		}
		RequestDispatcher dispatcher = request
				.getRequestDispatcher("../../temp/exportleads.xls");
		try {
			dispatcher.forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return NONE;
	}

	protected void fetchListData() {
		super.fetchListData();
		Map<String, String> map = new LinkedHashMap<String, String>();
		List<User> users = userService.findAllTm();
		for (User u : users) {
			map.put(u.getId().toString(), u.getName());
		}
		tms = map;

		Map<String, String> cmsMap = new LinkedHashMap<String, String>();
		List<User> cmUser = userService.findAllCm();
		for (User u2 : cmUser) {
			cmsMap.put(u2.getId().toString(), u2.getName());
		}
		cms = cmsMap;
	}

	public String assignToTm() {
		String ids = getRequest().getParameter("ids");
		String[] id = ids.split(",");
		String tm = getRequest().getParameter("tm_id");
		User user = userService.findById(Long.valueOf(tm));
		for (String i : id) {
			Leads l = leadsService.findById(Long.valueOf(i));
			if (l.getCreateUser() != null
					&& l.getCreateUser().getRole() != null
					&& l.getCreateUser().getRole().getName().equalsIgnoreCase(
							"CC")) {
				//CC创建的leads 不能 在分配给TM
				continue;
			}
			LeadsDealHistory dh = new LeadsDealHistory();
			dh.setCurState(user.getName());
			if (l.getTm() != null) {
				dh.setPreState(l.getTm().getName());
			}
			dh.setDealTime(new Date());
			dh.setOperUser(this.getSessionUser());
			dh.setType(ELeadsDealType.AssignedToTM);
			dh.setLeads(l);
			leadsDealHistoryService.saveOrUpdate(dh);
			l.setTm(user);
			l.setTmAssignTime(new Date());
			leadsService.saveOrUpdate(l);
		}
		fetchListData();
		return OK;
	}

	public String assignToCm() {
		String ids = getRequest().getParameter("ids");
		String[] id = ids.split(",");
		String cm = getRequest().getParameter("cm_id");
		User user = userService.findById(Long.valueOf(cm.trim()));
		for (String i : id) {
			Leads l = leadsService.findById(Long.valueOf(i.trim()));

			LeadsDealHistory dh = new LeadsDealHistory();
			if (l.getTm() != null) {
				dh.setPreState(l.getTm().getName());
			}
 			if (l.getCc() != null) {
				dh.setCurState(l.getCc().getName());
			}
			dh.setDealTime(new Date());
			dh.setOperUser(this.getSessionUser());
			dh.setType(ELeadsDealType.AssignedToCM);
			dh.setLeads(l);
			leadsDealHistoryService.saveOrUpdate(dh);
			//设置学校
			l.setSchool(user.getSchool());
			l.setCc(user);
			l.setCcAssignTime(new Date());
			l.setTm(user);
			leadsService.saveOrUpdate(l);
		}
		fetchListData();
		return OK;
	}

	public Map<String, String> getCms() {
		return cms;
	}

	public void setCms(Map<String, String> cms) {
		this.cms = cms;
	}

	public Map<String, String> getTms() {
		return tms;
	}

	public void setTms(Map<String, String> tms) {
		this.tms = tms;
	}

	public String getNoTm() {
		return noTm;
	}

	public void setNoTm(String noTm) {
		this.noTm = noTm;
	}

	public Boolean isTMManager() {
		if (getSessionUser().getRole().getName().trim().equalsIgnoreCase(
				"TM Manager")) {
			return true;
		} else {
			return false;
		}
	}
}
